#import "ApplePay.h"
#import <Cordova/CDV.h>
#import "UPAPayPlugin.h"
#import <PassKit/PassKit.h>

@implementation ApplePay

NSString* const UNIONPAY_MODE_KEY       = @"unionpaymode";
NSString* const RESULT_SUCCESS          = @"success";
NSString* const RESULT_FAIL             = @"fail";
NSString* const RESULT_CANCEL           = @"cancel";
NSString* const RESULT_UNKNOWNCANCEL_MESSAGE   = @"unknown_cancel";

- (void)pluginInitialize {
	/*
    NSString* mode = [[self.commandDelegate settings] objectForKey:UNIONPAY_MODE_KEY];

    NSLog(@"Get preference \"%@\": \"%@\"", UNIONPAY_MODE_KEY, mode);

    if (mode) {
        _mode = mode;
    } else {
        _mode = @"01";
    }

    NSLog(@"Initialized payment mode as \"%@\".", _mode);
    */
}

- (void)starPay:(CDVInvokedUrlCommand*)command
{
    _callbackId = command.callbackId;

    @try {
        NSString* tn = [command.arguments objectAtIndex:0];
		NSString* test_mode = [command.arguments objectAtIndex:1];
		NSString* merchant_id = [command.arguments objectAtIndex:2];
		
        NSLog(@"Start payment with transaction number \"%@\" and mode \"%@\".", tn, test_mode);
		
		/*CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"暂不支持Apple Pay"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];*/

		/*NSString* result = [NSString stringWithFormat:@"%@,%@,%@", tn, test_mode, merchant_id];
		CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:result];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];*/
		
		if ([UIDevice currentDevice].systemVersion.floatValue >= 9.2) {
			if ([PKPaymentAuthorizationViewController canMakePayments]) {
				if ([PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:@[PKPaymentNetworkChinaUnionPay,PKPaymentNetworkMasterCard,PKPaymentNetworkVisa]]) {
					  [UPAPayPlugin startPay:tn mode:test_mode viewController:self.viewController delegate:self andAPMechantID:merchant_id];
				} else {
					CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"请添加银行卡"];
					[self.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];
				}
			}
			else {
				CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"设备不支持Apple Pay"];
				[self.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];
			}
		}
		else  {
			CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"系统不支持Apple Pay"];
			[self.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];
		}
      
    }																							  
    @catch (NSException *exception) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[exception reason]];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];
    }
    @finally {

    }
}

//
-(NSString *)jsonStringWitchDictionary:(NSDictionary *)infoDict
{
    NSError *error =nil;
    NSData *jsonData =nil;
    
    jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&error];
    if([jsonData length] == 0 || error != nil){
        return nil;
    }
    NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    return jsonString;
}

- (void)UPAPayPluginResult:(UPPayResult *)result
{
    NSLog(@"Payment result message: \"%@\"", result);

    CDVPluginResult* pluginResult = nil;
	
	NSString *resultString = nil;
	NSMutableDictionary * resultDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                                 @"",@"pay_result",
                                                 @"",@"info",nil];
    
	
    if (result.paymentResultStatus == UPPaymentResultStatusSuccess)
    {
		NSString *otherInfo = result.otherInfo?result.otherInfo:@"";
		[resultDict setValue:RESULT_SUCCESS forKey:@"pay_result"];
		[resultDict setValue:otherInfo forKey:@"info"];
    }
    else if (result.paymentResultStatus == UPPaymentResultStatusFailure)
    {
		NSString *errorInfo = [NSString stringWithFormat:@"%@",result.errorDescription];
		[resultDict setValue:RESULT_FAIL forKey:@"pay_result"];
		[resultDict setValue:errorInfo forKey:@"info"];
    }
    else if (result.paymentResultStatus == UPPaymentResultStatusCancel)
    {
        [resultDict setValue:RESULT_CANCEL forKey:@"pay_result"];
    }
	else if (result.paymentResultStatus == UPPaymentResultStatusUnknownCancel)
    {
		/*TODO UPPAymentResultStatusUnknowCancel表示发起支付以后用户取消，导致支付状态不确认，需要查询商户后台确认真实的支付结果*/
		[resultDict setValue:RESULT_UNKNOWNCANCEL_MESSAGE forKey:@"pay_result"];
    }
	
	resultString = [self jsonStringWitchDictionary:resultDict];
	if (result.paymentResultStatus == UPPaymentResultStatusFailure)
	{
		pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:resultString];
	}
	else 
	{
		pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:resultString];
	}
    [self.commandDelegate sendPluginResult:pluginResult callbackId:_callbackId];
}

@end
